<template>
  <!-- 离线操作 -->
  <view class="tab-offline">
    <wd-cell
      custom-class="cell"
      :custom-value-class="`cell-value ${file.name ? 'light' : 'gray'}`"
      title="上传工单"
      :value="file.name || '请选择'"
      title-width="80px"
      size="large"
      is-link
      @click="chooseWorkOrderFile"
    />
    <view class="gap-h16"></view>
    <!-- <wd-cell
      title="输入协议"
      title-width="80px"
      size="large"
      custom-class="cell"
      custom-value-class="cell-value"
    >
      <view class="cell-value">
        <wd-input type="text" v-model="proto" placeholder="请输入或选择" no-border />
        <wd-picker :columns="protosColumns" v-model="proto" use-default-slot>
          <view class="picker" style="padding-left: 10px">
            <wd-icon name="arrow-right" size="16px"></wd-icon>
          </view>
        </wd-picker>
      </view>
    </wd-cell>
    <view class="gap-h16"></view> -->
    <view class="login-button" @click="onOffline">确定</view>
    <view class="tip">
      <text
        >如果连接不上服务器，可以选择离线操作；\n在有网络的情况下可以把操作结果数据回传至服务器。</text
      >
    </view>
  </view>
</template>

<script setup>
import { ref } from 'vue'
import * as XLSX from 'xlsx'
import { useOrderStore, useUserStore } from '@/stores/'
const orderStore = useOrderStore()
const userStore = useUserStore()
// 协议选择器数据
// const protosColumns = ref(['ariter', 'bluetork'])
// 协议值
// const proto = ref('')
// 文件
const file = ref({
  name: '',
  data: null,
  type: '',
})
// 选择文件
function chooseWorkOrderFile() {
  // #ifdef MP-WEIXIN
  wx.chooseMessageFile({
    count: 1,
    type: 'file',
    extension: ['xlsx', 'xls'],
    success(resFile) {
      console.log(resFile.tempFiles[0])
      const fs = wx.getFileSystemManager()
      // 打开文件
      fs.readFile({
        filePath: resFile.tempFiles[0].path,
        encoding: 'base64',
        position: 0,
        success(res) {
          file.value.name = resFile.tempFiles[0].name
          file.value.data = res.data
          file.value.type = 'base64'
        },
      })
    },
  })
  // #endif
  // #ifdef WEB
  uni.chooseFile({
    count: 1,
    type: 'file',
    extension: ['xlsx', 'xls'],
    async success(resFile) {
      console.log(resFile.tempFiles[0])
      // 读取文件
      const data = await new Promise((resolve, reject) => {
        const fileReader = new FileReader()
        fileReader.onload = (e) => {
          resolve(e.target.result)
        }
        fileReader.onerror = (error) => {
          reject(error)
        }
        fileReader.readAsArrayBuffer(resFile.tempFiles[0])
      })
      file.value.name = resFile.tempFiles[0].name
      file.value.data = data
      file.value.type = 'array'
    },
  })
  // #endif
  // #ifdef APP
  uni.$once('sendFileData', (fileData) => {
    file.value = fileData
  })
  uni.navigateTo({ url: '/pages/file/file' })
  // #endif
}
// 解析文件数据
function formatWorkData() {
  // 数值格式化函数
  function formatNumber(value) {
    if (typeof value === 'number' && !Number.isInteger(value)) {
      // 对于小数，保留合适的小数位数
      return parseFloat(value.toFixed(6))
    }
    return value
  }
  return new Promise((resolve, reject) => {
    let list = []
    // let fields = ['name', 'target_tork', 'tork_unit', 'min_tork', 'max_tork', 'angle', 'min_angle', 'max_angle', 'company_id', 'worktype', 'company_code', 'name_code', 'user', 'barcode','main_id'];
    let fields = [
      'name',
      'target_tork',
      'tork_unit',
      'min_tork',
      'max_tork',
      'angle',
      'min_angle',
      'max_angle',
      'company_id',
      'worktype',
      'company_code',
      'id',
      'user',
      'barcode',
      'main_id',
    ]
    try {
      // 解析 XLSX 文件
      const workbook = XLSX.read(file.value.data, { type: file.value.type })
      // 获取第一个工作表
      const firstSheetName = workbook.SheetNames[0]
      const fileArr = XLSX.utils.sheet_to_json(workbook.Sheets[firstSheetName], { header: 1 })
      console.log('fileArr', fileArr)
      fileArr.forEach((v, k) => {
        if (k > 0) {
          list.push({
            [fields[0]]: v[0],
            [fields[1]]: formatNumber(v[1]),
            [fields[2]]: v[2],
            [fields[3]]: formatNumber(v[3]),
            [fields[4]]: formatNumber(v[4]),
            [fields[5]]: formatNumber(v[5]),
            [fields[6]]: formatNumber(v[6]),
            [fields[7]]: formatNumber(v[7]),
            [fields[8]]: v[8],
            [fields[9]]: v[9],
            [fields[10]]: v[10],
            [fields[11]]: v[11],
            [fields[12]]: v[12],
            [fields[13]]: v[13],
            [fields[14]]: [v[15], v[14]],
          })
        }
      })
      console.log('list', list)
      resolve(list)
    } catch (error) {
      console.log('error', error)
      uni.$globalMessage.alert({
        msg: '读取文件失败',
        title: '提示',
      })
      reject(error)
    }
  })
}

async function onOffline() {
  if (!file.value.data) {
    uni.$globalMessage.alert({
      msg: '请上传工单文件',
      title: '提示',
    })
    return
  }
  // if (!proto.value || !protosColumns.value.includes(proto.value)) {
  //   uni.$globalMessage.alert({
  //     msg: '该设备不在系统中，请更换设备或者联系管理员',
  //     title: '提示',
  //   })
  //   return
  // }

  // if (!file.device) {
  //   wx.showModal({
  //     title: '请上传设备文件',
  //     showCancel: false
  //   });
  //   return;
  // }
  const datalist = await formatWorkData()
  orderStore.setOfflineOrderList(datalist)
  const userInfo = {
    name: datalist[0].user,
    env_company: datalist[0].company_id,
  }
  userStore.setUserInfo(userInfo)
  userStore.setActionType('offline')

  uni.navigateBack()
}
</script>

<style lang="scss" scoped>
.tab-offline {
  padding: 18px 14px;
  height: 100vh;
  // height: calc(100vh - 48px - var(--window-top));
  // height: calc(100vh - 48px - var(--window-top) - constant(safe-area-inset-bottom));
  // height: calc(100vh - 48px - var(--window-top) - env(safe-area-inset-bottom));
  background: $my-background-color-2;
  .cell {
    border-radius: $my-border-radius-base;
    :deep(.cell-value) {
      @include flex-box();
      width: 100%;
      text-align: left;
      color: $text-font-color-3;
      &.light {
        color: initial;
      }
      .wd-input__placeholder {
        font-size: initial;
      }
    }
  }
  .login-button {
    // box-shadow: 0 4px 15px #999;
    background: linear-gradient(90deg, #5235b1 0%, #246dd9 100%);
    color: white;
    border-radius: 10px;
    height: 44px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: 600;
    margin-top: 10px;
    box-shadow: 0 6px 15px rgba(26, 115, 232, 0.3);
    transition: all 0.3s;
    position: relative;
    overflow: hidden;
    &::after {
      content: '';
      position: absolute;
      top: 0;
      left: -100%;
      width: 200%;
      height: 100%;
      background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.4), transparent);
      transition: all 0.3s;
    }

    &:active {
      transform: translateY(3px);
      box-shadow: 0 3px 8px rgba(26, 115, 232, 0.3);
      &::after {
        left: 100%;
      }
    }
  }
  .tip {
    margin-top: 20px;
    font-size: $my-text-font-size-sm;
    color: $text-font-color-3;
  }
}
</style>
